package logic

import (
	"common/cron"
	"common/model"
	"common/pkg"
	"context"
	"fmt"
	"log"
	product "product_server/proto"
	"time"
)

// BargainSettlement 砍价结算
func (p *ProductServer) BargainSettlement(ctx context.Context, req *product.BargainSettlementRequest) (*product.BargainSettlementResponse, error) {
	// 1. 查询砍价订单信息
	orderBargain, err := model.GetOrderBargainInfo(req.OrderId)
	if err != nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "砍价订单不存在",
		}, nil
	}

	// 2. 验证砍价订单状态
	if orderBargain.Status != 1 {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "砍价未成功，无法结算",
		}, nil
	}

	// 3. 检查砍价是否已过期
	if time.Now().After(orderBargain.ExpireTime) {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "砍价已过期，无法结算",
		}, nil
	}

	// 4. 查询主订单信息，验证用户权限
	masterOrder, err := model.GetOrderCatInfo(orderBargain.OrderId)
	if err != nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "主订单不存在",
		}, nil
	}

	// 5. 验证用户权限（只有发起者可以结算）
	if masterOrder.UserId != req.UserId {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "无权限结算此砍价订单",
		}, nil
	}

	// 6. 检查主订单状态
	if masterOrder.Status != 3 { // 3表示待支付
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "订单状态异常，无法结算",
		}, nil
	}

	// 7. 查询砍价活动信息
	activityInfo, err := model.GteBargainActivity(orderBargain.ActivityId, masterOrder.ProductId)
	if err != nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "砍价活动不存在",
		}, nil
	}

	// 8. 检查砍价活动库存
	if activityInfo.Stock <= 0 {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "砍价商品库存不足",
		}, nil
	}

	// 9. 扣减砍价活动库存
	err = model.DeductBargainProductStock(activityInfo.Id)
	if err != nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "库存扣减失败",
		}, nil
	}

	// 10. 直接更新现有订单的实际价格为砍价后的价格
	masterOrder.ActualPrice = float64(orderBargain.CurrentPrice)
	masterOrder.UpdatedAt = time.Now()
	masterOrder.PaymentTime = time.Now()

	// 更新订单
	err = model.UpdateOrderMaster(masterOrder)
	if err != nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "订单更新失败",
		}, nil
	}

	// 11. 创建支付链接
	pay := pkg.NewPay()
	if pay == nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "支付服务初始化失败",
		}, nil
	}

	// 获取商品信息用于支付描述
	productInfo, err := model.GetProductInfo(masterOrder.ProductId)
	if err != nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "商品信息获取失败",
		}, nil
	}

	orderPrice := fmt.Sprintf("%.2f", masterOrder.ActualPrice)
	payUrl, err := pay.Pay("砍价商品-"+productInfo.StoreName, masterOrder.OrderNo, orderPrice)
	if err != nil {
		return &product.BargainSettlementResponse{
			Success: false,
			Message: "支付链接创建失败",
		}, nil
	}

	//获取订单id和订单号
	OrderId := masterOrder.Id
	OrderSn := masterOrder.OrderNo

	go cron.OrderUpdatePaidTime(OrderSn)
	log.Printf("订单处理完成，订单ID: %d, 订单号: %s", OrderId, OrderSn)

	return &product.BargainSettlementResponse{
		Success:       true,
		Message:       "砍价结算成功，请完成支付。支付链接：" + payUrl,
		OrderNo:       masterOrder.OrderNo,
		FinalPrice:    float32(masterOrder.ActualPrice),
		PaymentStatus: 3, // 3表示待支付
	}, nil
}
